<template>
  <view class="my-container">
    <!-- 用户信息卡片 -->
    <view class="user-card">
      <!-- 用户头像，可点击更换 -->
      <image
        class="avatar"
        :src="user.avatar || defaultAvatar"
        mode="aspectFill"
        @click="chooseAvatar"
      ></image>

      <view class="user-info">
        <!-- 用户名和手机号显示 -->
        <text class="username">{{ user.account || '未设置用户名' }}</text>
        <text class="phone">{{ user.phone || '未绑定手机号' }}</text>
      </view>
    </view>
	
	<!-- 退出登录按钮 -->
	<view class="logout-btn">
	  <button type="warn" @click="logout">退出登录</button>
	</view>

	<!-- 修改个人信息按钮 -->
	<view class="edit-btn">
	  <button type="primary" @click="openEditPopup">修改个人信息</button>
	</view>
	

	<uni-popup ref="editPopup" type="center">
	  <view class="popup-content">
		<text class="popup-title">修改个人信息</text>

		<view class="popup-item">
		  <text>用户名：</text>
		  <input v-model="editAccount" placeholder="请输入用户名" />
		</view>

		<view class="popup-item">
		  <text>手机号：</text>
		  <input v-model="editPhone" type="number" placeholder="请输入手机号" />
		</view>

		<view class="popup-item">
		  <text>邮箱：</text>
		  <input v-model="editEmail" placeholder="请输入邮箱号" />
		</view>

		<view class="popup-buttons">
		  <button size="mini" type="primary" @click="updateUserInfo">确认</button>
		  <button size="mini" @click="closeEditPopup">取消</button>
		</view>
	  </view>
	</uni-popup>
  </view>
</template>

<script setup>
import { ref } from 'vue'
// uni-app 在 vue3 + script setup 下直接提供 onShow hook
import { onShow } from '@dcloudio/uni-app'
import { request } from '@/utils/request.js'

// 导入封装好的用户 API
import {
  getGuestInfo,
  getWorkerInfo,
  updateWorkerPassword,
  updateGuestPassword,
  workerSelfUpdate,
  guestSelfUpdate
} from '@/utils/userApi.js'

// -------------------- 数据 --------------------
const user = ref({}) // 当前用户信息
const defaultAvatar = '/static/my-icons/default.png' // 默认头像
const showPwdModal = ref(false) // 弹窗是否显示
const showEditModal = ref(false) // 修改个人信息弹窗
const editAccount = ref('')
const editPhone = ref('')
const editEmail = ref('')
// 弹窗引用
const editPopup = ref(null)

// 打开/关闭弹窗方法
const openEditPopup = () => {
  editPopup.value.open()
}
const closeEditPopup = () => {
  editPopup.value.close()
}

// -------------------- 页面显示时获取用户信息 --------------------
onShow(async () => {
  const token = uni.getStorageSync('token')
  const role = uni.getStorageSync('role')
  if (!token) {
    // 如果未登录，跳转登录页
    console.log('未检测到登录信息，跳转登录页')
    uni.reLaunch({ url: '/pages/login/login' })
    return
  }

  try {
    let res = null
    // ✅【修改③】根据角色选择调用不同接口
    if (role === 'Worker') {
      res = await getWorkerInfo()
    } else if (role === 'Guest') {
      res = await getGuestInfo()
    }
    if (res) {
      user.value = res
      // 同步缓存到本地
      uni.setStorageSync('userInfo', res)
      console.log('用户信息', user.value)
	  user.value.avatar = user.value.avatar_url || '/static/my-icons/default.png'
    } else {
      uni.showToast({ title: '获取用户信息失败', icon: 'none' })
    }
  } catch (err) {
    console.error('获取用户信息接口报错', err)
    uni.showToast({ title: '获取用户信息失败', icon: 'none' })
  }
})

// -------------------- 用户选择头像 --------------------
const chooseAvatar = async () => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
	  // 获取文件信息（包括 size）
	  let fileSize = 0;
	  try {
	    const fileInfo = await uni.getFileInfo({ filePath: tempFilePath });
	    fileSize = fileInfo.size; // 字节大小
	  } catch (err) {
	    console.warn('获取文件信息失败', err);
	  }

	  // 1️⃣ 获取 OSS 上传策略
	  const ext = tempFilePath.split('.').pop().toLowerCase();
	  let mimeType = '';
	  if (ext === 'png') mimeType = 'image/png';
	  else if (ext === 'jpg' || ext === 'jpeg') mimeType = 'image/jpeg';
	  else if (ext === 'gif') mimeType = 'image/gif';
	  else if (ext === 'bmp') mimeType = 'image/bmp';
	  else mimeType = 'application/octet-stream'; 

	  const policyRes = await request({
	  url: '/image/policy',
	  method: 'POST',
	  data: { fileType: mimeType }, // ✅ 改成 MIME 格式
	  header: { 'Authorization': `Bearer ${uni.getStorageSync('token')}` }
	  });

      if (!policyRes || !policyRes.host) {
        return uni.showToast({ title: '获取上传策略失败', icon: 'none' })
      }

      // 2️⃣ 构造表单上传到 OSS
	  const fileName = tempFilePath.split('/').pop();
	  const key = policyRes.dir.endsWith('/') ? policyRes.dir + fileName : policyRes.dir + '/' + fileName;
      const formData = {
        key, 
        OSSAccessKeyId: policyRes.accessId,
        policy: policyRes.policy,
        signature: policyRes.signature,
        success_action_status: '200' // 返回 200 表示成功
      }

      uni.uploadFile({
        url: policyRes.host,       // 使用 host 作为 OSS 上传地址
        filePath: tempFilePath,
        name: 'file',              // OSS 要求字段名
        formData,
        success: async (uploadRes) => {
          //  OSS 回调，上传成功后通知后端
          const callbackRes = await request({
            url: '/image/callback',
            method: 'POST',
            data: {
				filename: policyRes.host + '/' + key, // 必须是 filename
				size: fileSize,                     // 可选
				mimeType: mimeType                // 可选
            },
            header: { 'Authorization': `Bearer ${uni.getStorageSync('token')}` }
          })

          // 更新本地显示
          user.value.avatar = callbackRes.filename // 后端返回的最终 URL
          uni.setStorageSync('userInfo', user.value)
          uni.showToast({ title: '头像上传成功', icon: 'success' })
		  console.log('url:',user.value)
        },
        fail: () => {
		  console.error('OSS 上传失败', err);
          uni.showToast({ title: '上传失败', icon: 'none' })
        }
      })
    }
  })
}

// -------------------- 获取用户头像 --------------------
const loadAvatar = async () => {
  try {
    const token = uni.getStorageSync('token')
    if (!token) return

    const res = await request({
      url: '/image/loadavatar',   // 对应后端接口
      method: 'POST',
      header: { 'Authorization': `Bearer ${token}` }
    })

    if (res) {
      // 假设后端直接返回的是头像 URL
      user.value.avatar = res
      uni.setStorageSync('userInfo', user.value)
      console.log('加载头像成功:', user.value.avatar)
    } else {
      console.warn('未获取到头像')
    }
  } catch (err) {
    console.error('获取头像接口报错', err)
  }
}

// -------------------- 保存用户信息（邮箱+头像） --------------------
const saveUserInfo = async () => {
  try {
    const role = uni.getStorageSync('role') // 增加角色判断
    let res = null

    if (role === 'Worker') {
      res = await workerSelfUpdate({
        email: user.value.email,
        avatar: user.value.avatar
      })
    } else {
      res = await guestSelfUpdate({
        email: user.value.email,
        avatar: user.value.avatar
      })
    }

    if (res) {
      uni.showToast({ title: '修改成功', icon: 'success' })
      uni.setStorageSync('userInfo', user.value)
    } else {
      uni.showToast({ title: '修改失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新用户信息失败', err)
    uni.showToast({ title: '修改失败', icon: 'none' })
  }
}

// -------------------- 修改用户名/手机号 --------------------
const updateUserInfo = async () => {
  if (!editAccount.value && !editPhone.value && !editEmail.value) {
    return uni.showToast({ title: '请输入要修改的信息', icon: 'none' })
  }

  try {
    const role = uni.getStorageSync('role') // 增加角色判断
    let res = null

    if (role === 'Worker') {
      res = await workerSelfUpdate({
        account: editAccount.value,
        phone: editPhone.value,
        email: editEmail.value
      })
    } else {
      res = await guestSelfUpdate({
        account: editAccount.value,
        phone: editPhone.value,
        email: editEmail.value
      })
    }


    if (typeof res === 'string' && res.includes('成功')) {
      uni.showToast({ title: '修改成功', icon: 'success' })
      closeEditPopup()
      // 同步更新本地信息
      if (editAccount.value) user.value.account = editAccount.value
      if (editPhone.value) user.value.phone = editPhone.value
	  if (editEmail.value) user.value.email = editEmail.value
      uni.setStorageSync('userInfo', user.value)
      // 清空输入
      editAccount.value = ''
      editPhone.value = ''
	  editEmail.value = ''
    } else {
      uni.showToast({ title: res || '修改失败', icon: 'none' })
    }
  } catch (err) {
    console.error('修改个人信息失败', err)
    uni.showToast({ title: '修改失败', icon: 'none' })
  }
}

// -------------------- 退出登录 --------------------
const logout = () => {
  uni.showModal({
    title: '退出登录',
    content: '确定要退出吗？',
    success: res => {
      if (res.confirm) {
        uni.removeStorageSync('token')
	    uni.removeStorageSync('role') // ✅【修改⑥】退出时清空角色信息
        uni.removeStorageSync('userInfo')
        uni.reLaunch({ url: '/pages/login/login' })
      }
    }
  })
}
</script>

<style lang="scss">
.my-container {
  padding: 30rpx;
}

/* 用户信息卡片 */
.user-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}
.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 30rpx;
}
.user-info {
  display: flex;
  flex-direction: column;
}
.username {
  font-size: 34rpx;
  font-weight: bold;
}
.phone {
  font-size: 28rpx;
  color: #888;
}

.logout-btn {
  margin-top: 60rpx;
}

/* 按钮区域 */
.edit-btn,
.logout-btn {
  margin-top: 40rpx;
}

/* 弹窗 */
.popup-content {
  background: #fff;
  padding: 40rpx;
  border-radius: 20rpx;
  width: 500rpx;
}
.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-align: center;
}
.popup-item {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}
.popup-item text {
  width: 140rpx;
  color: #555;
}
.popup-buttons {
  margin-top: 20rpx;
  display: flex;
  justify-content: space-around;
}
</style>
